package com.maple.phoneward.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

/**
 * StringUtils.java
 * 
 * @author: YaJian Qiu
 * @Time 2013-3-22 上午11:27:31<br>
 *       本类描述: 字符串工具类
 */
public final class StringUtil {

	private static final String TAG = "StringUtils";

	public static final Date stringToDate(String str, String pattern) {
		if (isEmpty(pattern))
			pattern = "yyyy-MM-dd hh:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.CHINA);
		Date date = null;
		try {
			date = sdf.parse(str);
		} catch (ParseException e) {
			e.printStackTrace();
			Logger.d(TAG, "字符串转日期类型错误");
		}
		return date;
	}

	/**
	 * 获取指定格式的日期字符串
	 * 
	 * @param date
	 * @param pattern
	 * @return
	 */
	public static final String dateToString(Date date, String pattern) {
		if (isEmpty(pattern))
			pattern = "yyyy-MM-dd hh:mm:ss";
		SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.CHINA);
		return sdf.format(date);
	}

	/**
	 * 去除字符串的空格
	 * 
	 * @param str
	 * @return
	 */
	public static final String trim(String str) {
		if (str != null && !"".equals(str)) {
			return str.trim();
		}
		return "";
	}

	/**
	 * 是否为空白字符串
	 * 
	 * @param str
	 * @return
	 */
	public static final boolean isEmpty(String str) {
		return "".equals(trim(str));
	}

	/**
	 * 不是空字符串
	 * 
	 * @param str
	 * @return
	 */
	public static final boolean isNotEmpty(String str) {
		return !isEmpty(str);
	}

	/**
	 * @param value1
	 * @param value2
	 * @return 比较两个字符串是否相等
	 */
	public static final boolean equals(String value1, String value2) {
		if (isEmpty(value1) && isEmpty(value2))
			return true;
		if (isEmpty(value1) || isEmpty(value2))
			return false;
		return value1.equals(value2);
	}

	/**
	 * @param value1
	 * @param value2
	 * @return 两个字符串不相等
	 */
	public static boolean notEquals(String value1, String value2) {
		return !equals(value1, value2);
	}

	/**
	 * @param value1
	 * @param value2
	 * @return value1是否包含value2，注意顺序
	 */
	public static boolean contains(String value1, String value2) {
		if (isEmpty(value1) || isEmpty(value2))// 排除“”包含“”的情况
			return false;
		return value1.contains(value2);
	}

	/**
	 * 获取6位随机密码，有0-9，a-z，A-Z组成
	 * 
	 * @return
	 */
	public static String getRandomPassword() {
		Random random = new Random();
		ArrayList<Character> nums = new ArrayList<Character>();
		for (int i = 0; i < 26; i++) {
			if (i < 10) {
				nums.add((char) (48 + i));
			}
			nums.add((char) (97 + i));
			nums.add((char) (65 + i));
		}
		String pwd = "";
		for (int i = 0; i < 6; i++) {
			pwd += nums.get(random.nextInt(nums.size()));
		}
		Logger.d(TAG, "Random pwd=[" + pwd + "]");
		return pwd;
	}

}
